package cn.hejiang.user.service.impl;

import cn.hejiang.basic.exception.BusinessException;
import cn.hejiang.basic.util.AjaxResult;
import cn.hejiang.basic.util.HttpClientUtils;
import cn.hejiang.basic.util.MD5Utils;
import cn.hejiang.basic.util.StrUtils;
import cn.hejiang.user.constant.UserConstants;
import cn.hejiang.user.domain.LoginInfo;
import cn.hejiang.user.domain.User;
import cn.hejiang.user.domain.WxUser;
import cn.hejiang.user.dto.LoginDto;
import cn.hejiang.user.mapper.LoginInfoMapper;
import cn.hejiang.user.mapper.UserMapper;
import cn.hejiang.user.mapper.WxUserMapper;
import cn.hejiang.user.service.ILoginService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LoginInfoMapper loginInfoMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public Map<String, Object> accountLogin(LoginDto loginDto) {
        // 校验参数不能为空
        if (StringUtils.isEmpty(loginDto.getUsername())
                || StringUtils.isEmpty(loginDto.getPassword())
                || StringUtils.isEmpty(loginDto.getType())) {
            throw new BusinessException("输入的账号或密码错误");
        }

        // 查询数据
        LoginInfo loginInfo = loginInfoMapper.loadByLoginDto(loginDto);
        // 未查询到数据
        if (loginInfo == null) {
            throw new BusinessException("输入的账号或密码错误");
        }

        // 查询到的校验密码
        String salt = loginInfo.getSalt();
        String md5Password = loginInfo.getPassword();

        // 比对密码是否一致
        String password = loginDto.getPassword();
        // 比对不一致报错
        System.out.println(MD5Utils.encrypByMd5(password+salt));
        if(!md5Password.equals(MD5Utils.encrypByMd5(password+salt))){
            throw new BusinessException("用户密码错误！！");
        }

        // 比对成功，保存redis token
        String token = UUID.randomUUID().toString();
        // 设置30分钟过期
        redisTemplate.opsForValue().set(token, loginInfo, 30, TimeUnit.MINUTES);
        // 返回token、loginInfo
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("loginInfo", loginInfo);
        // 敏感信息置空
        loginInfo.setSalt(null);
        loginInfo.setPassword(null);

        return map;

    }

    // 微信扫码登录
    @Override
    public AjaxResult wechat(Map<String, String> params) {
        String code = params.get("code");
        if (!StringUtils.hasLength(code)) { // 判断是否有授权码
            throw new BusinessException("无授权码");
        }

        // 到微信获取授权码
        String getTokenUrl = UserConstants.WXUSER_GET_TOKEN_URL
                .replace("APPID", UserConstants.APPID)
                .replace("SECRET", UserConstants.SECRET)
                .replace("CODE", code);

        // 通过code到微信获取token
        String tokenObjStr = HttpClientUtils.httpGet(getTokenUrl);
        JSONObject jsonObject = JSONObject.parseObject(tokenObjStr);
        String accessToken = jsonObject.getString("access_token"); // 令牌
        String openId = jsonObject.getString("openid"); // 微信号
        // 根据微信号查询t_wxuser
        WxUser wxUser = wxUserMapper.loadByOpenId(openId);
        // 判断微信用户是否已在平台绑定
        if (wxUser != null && wxUser.getUser_id() != null) {
            // 直接扫码登录，免密登录
            LoginInfo loginInfo = loginInfoMapper.loadByUserId(wxUser.getUser_id());
            // 登录成功保存redis、token
            String token = UUID.randomUUID().toString();
            // 设置30分钟过期时间
            redisTemplate.opsForValue().set(token, loginInfo, 30, TimeUnit.MINUTES);
            // 返回token loginInfo
            HashMap<String, Object> map = new HashMap<>();
            map.put("token", token);
            // 置空敏感信息
            loginInfo.setSalt(null);
            loginInfo.setPassword(null);
            map.put("loginInfo", loginInfo);

            return AjaxResult.me().setResultObj(map);
        }

        // 未找到曾经用户信息，第一次扫码转到绑定页面，并携带token、openId回去
        String binderUrlParams = "?accessToken="+accessToken+"&openId="+openId;
        return AjaxResult.me().setSuccess(false).setResultObj(binderUrlParams);
    }

    // 用户微信绑定
    @Override
    public Map<String, Object> binder(Map<String, String> params) {
        // 校验信息
        String phone = params.get("phone");
        String verifyCode = params.get("verifyCode");
        String accessToken = params.get("accessToken");
        String openId = params.get("openId");
        if (!StringUtils.hasLength(phone)
                || !StringUtils.hasLength(verifyCode)
                || !StringUtils.hasLength(accessToken)
                || !StringUtils.hasLength(openId)) {
            throw new BusinessException("必要信息为空");
        }

        // 验证是否已过期
        Object codeTmp = redisTemplate.opsForValue().get(UserConstants.BUSINESS_BINDER_PREFIX + phone);
        if (codeTmp == null) {
            throw new BusinessException("验证码已过期，请重新获取");
        }

        // 验证码是否相等，不区分大小写
        String code = codeTmp.toString().split(":")[0];
        if (!verifyCode.equalsIgnoreCase(code)) {
            throw new BusinessException("验证码输入错误");
        }

        // 手机不能被注册
        User userTmp = userMapper.loadByPhone(phone);
        User user = null;
        LoginInfo loginInfo = null;
        if (userTmp != null) {// 曾经已经注册过了，可以直接绑定微信用户
            user = userTmp;
            loginInfo = loginInfoMapper.loadById(user.getLogininfo_id());
        } else { // 没有用户，创建用户
            user = initUser(phone);
            loginInfo = user2LoginInfo(user);
            loginInfoMapper.save(loginInfo);
            user.setLogininfo_id(loginInfo.getId());
            userMapper.save(user);
        }

        // 通过token openId获取用户信息
        String getUserUrl = UserConstants.WXUSER_GET_USER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String wxUserTmp = HttpClientUtils.httpGet(getUserUrl);
        // 生成wxuser信息绑定平台用户
        WxUser wxUser = initWxUser(wxUserTmp, user);
        wxUserMapper.save(wxUser);
        // 登录成功保存redis、token
        String token = UUID.randomUUID().toString();
        // 设置30分钟过期时间
        redisTemplate.opsForValue().set(token, loginInfo, 30, TimeUnit.MINUTES);
        // 返回token loginInfo
        HashMap<String, Object> map = new HashMap<>();
        map.put("token", token);
        // 置空敏感信息
        loginInfo.setSalt(null);
        loginInfo.setPassword(null);
        map.put("loginInfo", loginInfo);

        return map;
    }

    private User initUser(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        // 盐值
        String salt = StrUtils.getComplexRandomString(32);
        // 使用盐值加密之后的密码，生成随机密码并发短信通知用户
        String md5Pwd = MD5Utils.encrypByMd5("12" + salt);
        user.setSalt(salt);
        user.setPassword(md5Pwd);
        return user;
    }

    private LoginInfo user2LoginInfo(User user) {
        LoginInfo loginInfo = new LoginInfo();
        BeanUtils.copyProperties(user, loginInfo);
        loginInfo.setType(1);
        return loginInfo;
    }

    private WxUser initWxUser(String wxUserTmp, User user) {
        // 微信用户信息
        JSONObject jsonObject = JSONObject.parseObject(wxUserTmp);
        WxUser wxUser =  new WxUser();
        wxUser.setUser_id(user.getId());//绑定用户
        wxUser.setOpenid(jsonObject.getString("openid"));
        wxUser.setNickname(jsonObject.getString("nickname"));
        wxUser.setSex(jsonObject.getInteger("sex"));
        wxUser.setAddress(null);
        wxUser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxUser.setUnionid(jsonObject.getString("unionid"));
        return wxUser;
    }
}
